package com.xjc.business.controller;

import com.xjc.system.constants.MyConstants;
import com.xjc.system.exception.MyException;
import com.xjc.system.result.Result;
import com.xjc.system.result.ResultCode;
import com.xjc.system.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 徐锦程
 * 时间:2025-01-26 11:04
 */
@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {

    @Value("${file.uploadPath}")
    String filePath;

    /**
     * 上传文件
     * @param file 文件
     * @return 结果
     */
    @PostMapping("/upload/{token}")
    public Result<String> uploadFile(@RequestParam("file") MultipartFile file,@PathVariable(value = "token",required = false) String token) {
        if (token==null|| !TokenUtils.isTokenValid(token)){
            throw new MyException(ResultCode.UNAUTHORIZED.getCode(),ResultCode.UNAUTHORIZED.getMessage());
        }
        if (file.isEmpty()) {
            throw new MyException(ResultCode.SUCCESS.getCode(), MyConstants.PARAM_MISSING);
        }
        try {
            // 创建目录（如果不存在）
            Path uploadPath = Paths.get(filePath);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 保存文件
            byte[] bytes = file.getBytes();
            Path path = Paths.get(filePath + file.getOriginalFilename());
            Files.write(path, bytes);

            return Result.okWithData(file.getOriginalFilename());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Result.okWithData("上传异常，稍后重试");
    }

    /**
     * 下载文件
     * @param filename 文件名
     * @return 文件流
     */
    @GetMapping("/download/{filename:.+}/{token}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String filename,@PathVariable(value = "token",required = false) String token) {
        if (token==null|| !TokenUtils.isTokenValid(token)){
            throw new MyException(ResultCode.UNAUTHORIZED.getCode(),ResultCode.UNAUTHORIZED.getMessage());
        }
        if (filename==null||filename.isEmpty()){
            throw new MyException(ResultCode.SUCCESS.getCode(), MyConstants.PARAM_MISSING);
        }
        try {
            Path path = Paths.get(filePath).resolve(filename);
            Resource resource = new FileSystemResource(path.toFile());
            if (resource.exists() || resource.isReadable()) {
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
}